﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;

namespace Technoera.Common.Interop.OleDb
{
    public class OneToOneImportMapping : IImportMapping
    {
        public OneToOneImportMapping(string sourceColumnName, PropertyInfo targetPropertyInfo)
        {
            if (string.IsNullOrEmpty(sourceColumnName)) throw new ArgumentException("sourceColumnName can not be empty.");
            if (targetPropertyInfo == null) throw new ArgumentNullException("targetPropertyInfo");
            SourceColumnName = sourceColumnName;
            TargetPropertyInfo = targetPropertyInfo;
        }

        public OneToOneImportMapping(string sourceColumnName, PropertyInfo targetPropertyInfo, Type targetPropertyConversionType)
            : this(sourceColumnName, targetPropertyInfo)
        {
            if (targetPropertyConversionType == null) throw new ArgumentNullException("targetPropertyConversionType");
            TargetPropertyConversionType = targetPropertyConversionType;
        }

        private string _sourceColumnName;
        public string SourceColumnName
        {
            get
            {
                if (_sourceColumnName == null)
                    _sourceColumnName = string.Empty;

                return _sourceColumnName;
            }
            set
            {
                _sourceColumnName = value;
            }
        }
	
        public PropertyInfo TargetPropertyInfo { get; set; }

        public Type TargetPropertyConversionType { get; set; }

        #region IImportMapping Members
        public void SetPropertyValue(IDataReader dataReader, object instance)
        {
            if (dataReader == null) throw new ArgumentNullException("dataReader");
            if (instance == null) throw new ArgumentNullException("instance");
            object sourceValue = dataReader[SourceColumnName];
            if (sourceValue is System.DBNull || sourceValue == null) return;
            if (TargetPropertyInfo == null) throw new NullReferenceException("TargetPropertyInfo can not be null.");
            if (TargetPropertyConversionType == null)
            {
                TargetPropertyInfo.SetValue(instance, sourceValue, null);
            }
            else
            {
                sourceValue = Convert.ChangeType(sourceValue, TargetPropertyConversionType);
                TargetPropertyInfo.SetValue(instance, sourceValue, null);
            }
        }
        #endregion
    }
}
